﻿using System;
using System.Text;
using IceCS.DataStructure.Core.LinearList;
using IceCS.DataStructure.Helpers;

namespace IceCS.DataStructure.StudentScore
{
    /// <summary>
    /// 
    /// </summary>
    public class StudentScoreManager
    {
        private ILinarList<StudentModel> _studentList;
        public StudentScoreManager()
        {

        }

        public void Run()
        {
            InitStorageStructure();
            MainLoop();
        }

        /// <summary>
        /// 初始化存储结构
        /// </summary>
        private void InitStorageStructure()
        {
            var tips = "请选择存储结构的类型：\n1.顺序表\n2.单向链表\n3.双向链表\n4.循环双向链表";
            var input = ConsoleHelper.GetRightInputNumber(tips,1,4);
            switch (input)
            {
                case 1:
                    int maxCount = ConsoleHelper.GetRightInputNumberGreatThanMinValue("请输入学生总人数(不小于 3):", 3);
                    _studentList = new SequenceList<StudentModel>(maxCount);
                    break;
                case 2:
                    _studentList = new SingleLinkedList<StudentModel>();
                    break;
                case 3:
                    _studentList = new DoublyLinkedList<StudentModel>();
                    break;
                case 4:
                    _studentList = new CircularDoublyLinkedList<StudentModel>();
                    break;
            }
        }

        /// <summary>
        /// 主循环
        /// </summary>
        private void MainLoop()
        {
            var isQuit = false;
            while (!isQuit)
            {
                var action = GetActionNo();
                switch (action)
                {
                    case 1:
                        AddStudentScore();
                        break;
                    case 2:
                        DeleteStudentScore();
                        break;
                    case 3:
                        FindStudentScoreByName();
                        break;
                    case 4:
                        FindStudentScoreById();
                        break;
                    case 5:
                        ShowStudentScore();
                        break;
                    case 6:
                        ShowStudentScoreAsc();
                        break;
                    case 7:
                        ShowStudentScoreDesc();
                        break;
                    case 8:
                        AddTestData();
                        break;
                    case 9:
                        isQuit = ConfirmQuit();
                        break;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void AddStudentScore()
        {
            var isContinue = !_studentList.IsFull;
            while (isContinue)
            {
                string id;
                string name;
                int score;
                id = ConsoleHelper.GetRightInputString("请输入学号：", str => !string.IsNullOrWhiteSpace(str));

                name = ConsoleHelper.GetRightInputString("请输入姓名：", str => !string.IsNullOrWhiteSpace(str));

                score = ConsoleHelper.GetRightInputNumberGreatThanMinValue("请输入成绩：", 0);

                StudentModel newNode = new StudentModel(id, name, score);

                _studentList.Add(newNode);

                Console.WriteLine("添加成功");
                if (_studentList.IsFull)
                {
                    Console.WriteLine("列表已满，无法录入新的数据");
                    isContinue = false;
                }
                else
                {
                    var inputResult = ConsoleHelper.GetRightInputString("还有学生成绩输入吗(Y/N)：", new string[] { "Y", "y", "N", "n" });
                    inputResult = inputResult.ToLower();
                    isContinue = inputResult == "y";
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void DeleteStudentScore()
        {
            if (_studentList.IsEmpty)
            {
                Console.WriteLine("列表为空，无数据可删除");
                return;
            }

            Console.WriteLine("请输入要删除学生的学号：");
            string studentId = Console.ReadLine();
            StudentModel student = _studentList.Find(s => s.Id == studentId);

            if (student == null)
            {
                Console.WriteLine("学号不存在，请检查是否输入正确");
                return;
            }
            _studentList.Remove(student);
            Console.WriteLine("删除成功");
        }

        /// <summary>
        /// 
        /// </summary>
        private void FindStudentScoreByName()
        {
            if (_studentList.IsEmpty)
            {
                Console.WriteLine("列表为空，无数据可查");
                return;
            }
            StudentModel student;
            var isFound = false;
            Console.WriteLine("请输入要查询学生的姓名：");
            string studentName = Console.ReadLine();
            for (int i = 0; i < _studentList.Count; i++)
            {
                student = _studentList.FindIndex(i);
                if (student.Name == studentName)
                {
                    isFound = true;
                    student = _studentList.FindIndex(i);
                    Console.WriteLine(student.ToString());
                    break;
                }
            }
            if (!isFound)
            {
                Console.WriteLine("符合姓名的学生不存在，请检查是否输入正确");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void FindStudentScoreById()
        {
            if (_studentList.IsEmpty)
            {
                Console.WriteLine("列表为空，无数据可查");
                return;
            }
            StudentModel student;
            var isFound = false;
            Console.WriteLine("请输入要查询学生的学号：");
            string studentId = Console.ReadLine();
            for (int i = 0; i < _studentList.Count; i++)
            {
                student = _studentList.FindIndex(i);
                if (student.Id == studentId)
                {
                    isFound = true;
                    student = _studentList.FindIndex(i);
                    Console.WriteLine(student.ToString());
                    break;
                }
            }
            if (!isFound)
            {
                Console.WriteLine("符合 id 的学生不存在，请检查是否输入正确");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void ShowStudentScoreAsc()
        {
            var students = new StudentModel[_studentList.Count];
            for (int i = 0; i < _studentList.Count; i++)
            {
                students[i] = _studentList.FindIndex(i);
            }
            for (int i = 0; i < students.Length - 1; i++)
            {
                for (int j = i + 1; j < students.Length; j++)
                {
                    var a = students[i];
                    var b = students[j];
                    if (a.Score > b.Score)
                    {
                        var tmp = a;
                        students[i] = b;
                        students[j] = tmp;
                    }
                }
            }
            Console.WriteLine("学号\t姓名\t成绩");
            for (int i = 0; i < students.Length; i++)
            {
                var student = students[i];
                Console.WriteLine("{0}\t{1}\t{2}", student.Id, student.Name,
                   student.Score);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void ShowStudentScoreDesc()
        {
            var students = new StudentModel[_studentList.Count];
            for (int i = 0; i < _studentList.Count; i++)
            {
                students[i] = _studentList.FindIndex(i);
            }
            for (int i = 0; i < students.Length - 1; i++)
            {
                for (int j = i + 1; j < students.Length; j++)
                {
                    var a = students[i];
                    var b = students[j];
                    if (a.Score < b.Score)
                    {
                        var tmp = a;
                        students[i] = b;
                        students[j] = tmp;
                    }
                }
            }
            Console.WriteLine("学号\t姓名\t成绩");
            for (int i = 0; i < students.Length; i++)
            {
                var student = students[i];
                Console.WriteLine("{0}\t{1}\t{2}", student.Id, student.Name,
                   student.Score);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void ShowStudentScore()
        {
            Console.WriteLine("学号\t姓名\t成绩");
            for (int i = 0; i < _studentList.Count; i++)
            {
                var student = _studentList.FindIndex(i);
                Console.WriteLine("{0}\t{1}\t{2}", student.Id, student.Name,
                   student.Score);
            }
        }

        /// <summary>
        /// 插入10条测试数据，如果是顺序表存储，则根据 MaxCount来判断，最多10条
        /// </summary>
        private void AddTestData()
        {
            if (!_studentList.IsEmpty)
            {
                Console.WriteLine("只有空列表可以插入测试数据");
                return;
            }
            var maxCount = 10;
            if (_studentList is SequenceList<StudentModel> seqList)
            {
                maxCount = seqList.MaxCount;
                if (maxCount > 10)
                {
                    maxCount = 10;
                }
            }
            var ran = new Random();
            for (int i = 0; i < maxCount; i++)
            {
                var id = i + 1;
                _studentList.Add(new StudentModel(
                    id: id.ToString(),
                    name: "student" + id.ToString(),
                    score: ran.Next(20, 150)
                    ));
            }
            Console.WriteLine($"成功添加 {maxCount} 条数据");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private bool ConfirmQuit()
        {
            string tips = "确定要退出嘛？（Y/N）";
            var result = ConsoleHelper.GetRightInputString(tips, new string[] { "Y", "y", "N", "n" });
            return result.ToLower() == "y";
        }

        /// <summary>
        /// 获得动作编号
        /// </summary>
        private int GetActionNo()
        {
            var sb = new StringBuilder();
            sb.AppendLine("---------------------------");
            sb.AppendLine("请输入操作选项：");
            sb.AppendLine("1：添加学生成绩");
            sb.AppendLine("2：删除学生成绩");
            sb.AppendLine("3：按姓名查询学生成绩");
            sb.AppendLine("4：按学号查询学生成绩");
            sb.AppendLine("5：显示所有学生成绩");
            sb.AppendLine("6：按升序显示所有学生成绩");
            sb.AppendLine("7：按降序显示所有学生成绩");
            sb.AppendLine("8：添加几条随机数据");
            sb.AppendLine("9：退出");


            var tips = sb.ToString();
            var index = ConsoleHelper.GetRightInputNumber(tips, num => num >= 1 && num <= 9);
            return index;
        }
    }
}
